package com.yunxi.service.sap.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yunxi.core.util.StringUtil;
import com.yunxi.eai.pojo.sap.*;
import com.yunxi.core.base.Constant;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.eai.pojo.esb.EsbVO;
import com.yunxi.eai.service.sap.SapService;
import com.yunxi.hubToBaseData.pojo.SapVehiclePriceVo;
import com.yunxi.hubToBaseData.service.BaseDataSaveService;
import com.yunxi.hubToBaseData.service.Sap2baseDataDubboService;
import com.yunxi.hubToBiz.pojo.*;
import com.yunxi.hubToBiz.service.ProducePlanBakDubboService;
import com.yunxi.hubToBiz.service.PushOrderReceiptDubboService;
import com.yunxi.model.eai.EaiLog;
import com.yunxi.parts.pojo.EaiSapPartCreateReqVO;
import com.yunxi.parts.pojo.EaiWaybillCreateReqVO;
import com.yunxi.parts.pojo.PrEpcPartPriceCreateReqVO;
import com.yunxi.parts.service.EaiEpcPartPriceDubboService;
import com.yunxi.parts.service.EaiPartDubboService;
import com.yunxi.parts.service.EaiWaybillDubboService;
import com.yunxi.rocketmq.producer.EaiLogsProducer;
import com.yunxi.sapToBiz.service.SapVehicleDeliveryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2019/5/28.
 */
@Service
@Qualifier("sapServiceImpl")
public class SapServiceImpl implements SapService {
    private static final Logger logger = LoggerFactory.getLogger(SapServiceImpl.class);

    @Autowired
    private EaiLogsProducer eaiLogsProducer;
    @Autowired
    private ProducePlanBakDubboService producePlanBakDubboServiceImpl;
    @Autowired
    private SapVehicleDeliveryService sapVehicleDeliveryServiceFromBiz;
    @Autowired
    private Sap2baseDataDubboService sap2baseDataDubboServiceImpl;
    @Autowired
    private PushOrderReceiptDubboService pushOrderReceiptDubboServiceImpl;
    @Autowired
    private EaiEpcPartPriceDubboService eaiEpcPartPriceDubboServiceImpl;
    @Autowired
    private EaiWaybillDubboService eaiWaybillDubboServiceImpl;

    @Autowired
    private EaiPartDubboService eaiPartDubboServiceImpl;
    @Override
    public ApiResult distributeSap(EsbVO esbVO) throws Exception {
        String serviceName = esbVO.getServiceName();
        String reqBody = esbVO.getReqBody();
        ApiResult apiResult = null;
        if (serviceName.equals(Constant.SAP_WEEK_PLAN_BACK)) {
            //周计划回传
            apiResult=weekPlanBack(esbVO);
        } else if (serviceName.equals(Constant.SAP_MONTH_PLAN_BACK)) {
            //月计划回传
            apiResult=monthPlanBack(esbVO);
        }else if(serviceName.equals(Constant.SAP_PMS_VEHICLE_DELIVERY_ORDER)){
            //车辆外向发货单接口
            apiResult = vechileDeliveryOrder(esbVO);
        } else if(serviceName.equals(Constant.SAP_VEHICLE_PRICE)){
            //车辆价格
            apiResult = vechilePrice(esbVO);
        } else if(serviceName.equals(Constant.SAP_MAKER_INVOICE)){
            //开票信息
            apiResult = makeInvoice(esbVO);
        }else if(serviceName.equals(Constant.SAP_UPS_PARTS_BILL)){
            //发运单
            apiResult = savePartsBill(esbVO);
        }else if(serviceName.equals(Constant.SAP_UPS_PARTS_PRICE)){
            //配件主数据价格同步
            apiResult = savePartsPrice(esbVO);
        }else if(serviceName.equals(Constant.SAP_UPS_PARTS)){
            //配件主数据同步
            apiResult = saveParts(esbVO);
        }else if(serviceName.equals(Constant.SAP_UPS_PARTS_ALLOT)){
            //配件调拨发运单
            apiResult = savePartsAllot(esbVO);
        }
        else {
            apiResult= ResponseUtil.fail(500,"没有对应的业务接口!");
        }
        return apiResult;
    }

    private ApiResult savePartsAllot(EsbVO esbVO) {
        ApiResult apiResult = null;
        EaiLog eaiLog=new EaiLog();
        String reqBody = esbVO.getReqBody();
        eaiLog.setEsbEaiContent(esbVO.getReqBody());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("ESB发送配件配件调拨发运单给UPS");
        eaiLog.setSourceSystem(Constant.UPSPARTS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            //内部业务
            JSONObject jsonObject = JSON.parseObject(reqBody);
            List<EaiWaybillCreateReqVO> var1=JSON.parseObject(String.valueOf( jsonObject.get("lists")), new TypeReference<ArrayList<EaiWaybillCreateReqVO>>() {});
            apiResult=eaiWaybillDubboServiceImpl.save4transfer(var1);
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));

        }catch (Exception e){
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(),e);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        return apiResult;
    }

    private ApiResult saveParts(EsbVO esbVO) {
        ApiResult apiResult = null;
        EaiLog eaiLog=new EaiLog();
        String reqBody = esbVO.getReqBody();
        eaiLog.setEsbEaiContent(esbVO.getReqBody());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("ESB发送配件主数据给UPS");
        eaiLog.setSourceSystem(Constant.UPSPARTS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            //内部业务
            JSONObject jsonObject = JSON.parseObject(reqBody);
            List<EaiSapPartCreateReqVO> var1= JSON.parseObject(String.valueOf( jsonObject.get("lists")), new TypeReference<ArrayList<EaiSapPartCreateReqVO>>() {});
            apiResult= eaiPartDubboServiceImpl.saveSapParts(var1);
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));

        }catch (Exception e){
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(),e);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        return apiResult;
    }

    private ApiResult savePartsPrice(EsbVO esbVO) {
        ApiResult apiResult = null;
        EaiLog eaiLog=new EaiLog();
        String reqBody = esbVO.getReqBody();
        eaiLog.setEsbEaiContent(esbVO.getReqBody());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("ESB发送配件主数据价格给UPS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            //内部业务
            JSONObject jsonObject = JSON.parseObject(reqBody);
            ArrayList<PrEpcPartPriceCreateReqVO> var1 = JSON.parseObject(String.valueOf( jsonObject.get("lists")), new TypeReference<ArrayList<PrEpcPartPriceCreateReqVO>>() {});
            // List<PrEpcPartPriceCreateReqVO> var1=JSON.parseObject(reqBody, new TypeReference<ArrayList<PrEpcPartPriceCreateReqVO>>() {});
            apiResult= eaiEpcPartPriceDubboServiceImpl.save(var1);
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));

        }catch (Exception e){
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(),e);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        return apiResult;
    }

    private ApiResult savePartsBill(EsbVO esbVO) {
        ApiResult apiResult = null;
        EaiLog eaiLog=new EaiLog();
        String reqBody = esbVO.getReqBody();
        eaiLog.setEsbEaiContent(esbVO.getReqBody());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("ESB发送发运单给UPS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        JSONObject jsonObject = JSON.parseObject(reqBody);
        try {
         ArrayList<EaiWaybillCreateReqVO> var1 = JSON.parseObject(String.valueOf( jsonObject.get("lists")), new TypeReference<ArrayList<EaiWaybillCreateReqVO>>() {});
            apiResult=eaiWaybillDubboServiceImpl.save(var1);
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));

        }catch (Exception e){
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(),e);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        return apiResult;
    }

    private ApiResult makeInvoice(EsbVO esbVO) {
        ApiResult apiResult = null;
        EaiLog eaiLog=new EaiLog();
        String reqBody = esbVO.getReqBody();
        eaiLog.setEsbEaiContent(esbVO.getReqBody());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("ESB发送开票信息给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        JSONObject jsonObject = JSON.parseObject(reqBody);
        ArrayList<MakeInvoiceVO> makeInvoice = JSON.parseObject(String.valueOf( jsonObject.get("lists")), new TypeReference<ArrayList<MakeInvoiceVO>>() {});
        try {
            //内部业务
            //pushOrderReceiptDubboServiceImpl
            for (int i = 0; i < makeInvoice.size(); i++) {
                MakeInvoiceVO makeInvoiceVO =  makeInvoice.get(i);
                PushOrderReceiptReqVO pushOrderReceiptReqVO=new PushOrderReceiptReqVO();
                BeanUtils.copyProperties(makeInvoiceVO,pushOrderReceiptReqVO);
                pushOrderReceiptDubboServiceImpl.pushOrderReceipt(pushOrderReceiptReqVO);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            apiResult=ResponseUtil.ok();
        }catch (Exception e){
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(),e);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        return apiResult;
    }

    private ApiResult vechilePrice(EsbVO esbVO) {
        ApiResult apiResult = null;
        EaiLog eaiLog=new EaiLog();
        String reqBody = esbVO.getReqBody();
        eaiLog.setEsbEaiContent(esbVO.getReqBody());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("ESB发送整车价格给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        JSONObject jsonObject = JSON.parseObject(reqBody);
        ArrayList<VehiclePriceVo> vehiclePrice = JSON.parseObject(String.valueOf( jsonObject.get("lists")), new TypeReference<ArrayList<VehiclePriceVo>>() {});
        try {
            //内部业务
            ArrayList<SapVehiclePriceVo> sapVehiclePrice=new ArrayList<>();
            for (int i = 0; i < vehiclePrice.size(); i++) {
                VehiclePriceVo vehiclePriceVo =  vehiclePrice.get(i);
                SapVehiclePriceVo sapVehiclePriceVo=new SapVehiclePriceVo();
                BeanUtils.copyProperties(vehiclePriceVo,sapVehiclePriceVo);
                sapVehiclePrice.add(sapVehiclePriceVo);
            }
            sap2baseDataDubboServiceImpl.saveVehiclePrice(sapVehiclePrice);
          /*  if (apiResult.getCode()==-1){
                eaiLog.setDisposeStatus(2);
            }*/
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
        }catch (Exception e){
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(),e);
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //  SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        return apiResult;
    }


    private ApiResult monthPlanBack(EsbVO esbVO) {
        ApiResult apiResult = null;
        EaiLog eaiLog=new EaiLog();
        String reqBody = esbVO.getReqBody();
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("ESB发送月计划返回信息给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        JSONObject jsonObject = JSON.parseObject(reqBody);
        ArrayList<MonthPlanResultVO> monthPlanList = JSON.parseObject(String.valueOf( jsonObject.get("return")), new TypeReference<ArrayList<MonthPlanResultVO>>() {});
        try {
            //内部业务
            ArrayList<MonthPlanBackVO> monthPlanBackList=new ArrayList<>();
            for (int i = 0; i < monthPlanList.size(); i++) {
                MonthPlanResultVO monthPlanResultVO =  monthPlanList.get(i);
                MonthPlanBackVO monthPlanBackVO=new MonthPlanBackVO();
                BeanUtils.copyProperties(monthPlanResultVO,monthPlanBackVO);
                monthPlanBackList.add(monthPlanBackVO);
            }
            producePlanBakDubboServiceImpl.monthBackProc(monthPlanBackList);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
        }catch (Exception e){
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(),e);
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //  SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return  apiResult;
    }

    private ApiResult weekPlanBack(EsbVO esbVO) {
        ApiResult apiResult = null;
        EaiLog eaiLog=new EaiLog();
        String reqBody = esbVO.getReqBody();
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("ESB发送周计划返回信息给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        JSONObject jsonObject = JSON.parseObject(reqBody);
        ArrayList<WeekPlanResultVO> weekPlanList = JSON.parseObject(String.valueOf( jsonObject.get("return")), new TypeReference<ArrayList<WeekPlanResultVO>>() {});
        try {
            //内部业务
            //内部业务
            ArrayList<WeekPlanBackVO> weekPlanBackVOList=new ArrayList<>();
            for (int i = 0; i < weekPlanList.size(); i++) {
                WeekPlanResultVO weekPlanResultVO =  weekPlanList.get(i);
                WeekPlanBackVO weekPlanBackVO=new WeekPlanBackVO();
                BeanUtils.copyProperties(weekPlanResultVO,weekPlanBackVO);
                weekPlanBackVOList.add(weekPlanBackVO);
            }
            producePlanBakDubboServiceImpl.weekBackProc(weekPlanBackVOList);
            apiResult=ResponseUtil.ok();
            if (apiResult.getCode()==-1){
                eaiLog.setDisposeStatus(2);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
        }catch (Exception e){
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(),e);
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //  SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        return apiResult;
    }


    /**
     * 车辆外向发货单接口
     * @param esbVO
     * @return
     */
    private ApiResult vechileDeliveryOrder(EsbVO esbVO){
        ApiResult apiResult = null;
        EaiLog eaiLog=new EaiLog();
        String reqBody = esbVO.getReqBody();
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("ESB发送车辆外向发货单给PMS");
        eaiLog.setSourceSystem(Constant.SAP);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        JSONObject jsonObject = JSON.parseObject(reqBody);
        ArrayList<VehicleDeliveryOrderVO> vehicleDeliveryOrderList = JSON.parseObject(String.valueOf( jsonObject.get("lists")), new TypeReference<ArrayList<VehicleDeliveryOrderVO>>() {});
        try {
            //内部业务

            apiResult = sapVehicleDeliveryServiceFromBiz.saveVehicleDelivery(vehicleDeliveryOrderList);

//            apiResult=ResponseUtil.ok();
            if (apiResult.getCode()==-1){
                eaiLog.setDisposeStatus(2);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
        }catch (Exception e){
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(),e);
        }
        // Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //    SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        return apiResult;
    }

}
